package com.smartcampusbackend.util;

import com.smartcampusbackend.model.User;
import com.smartcampusbackend.model.SystemLog;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {
    public static List<User> readUsersFromExcel(MultipartFile file) throws Exception {
        List<User> userList = new ArrayList<>();
        InputStream is = file.getInputStream();
        Workbook workbook = new XSSFWorkbook(is);
        Sheet sheet = workbook.getSheetAt(0);
        int firstRow = 1; // 跳过表头
        for (int i = firstRow; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;
            User user = new User();
            user.setUsername(getCellString(row, 0));
            user.setPassword(getCellString(row, 1)); // 建议前端要求初始密码
            user.setRealName(getCellString(row, 2));
            user.setRole(getCellString(row, 3));
            user.setEmail(getCellString(row, 4));
            user.setPhone(getCellString(row, 5));
            user.setStatus(1); // 默认正常
            userList.add(user);
        }
        workbook.close();
        return userList;
    }

    /**
     * 导出任意类型数据到Excel
     */
    public static byte[] exportToExcel(String sheetName, String[] headers, String[] fields, List<?> dataList) {
        try (Workbook workbook = new XSSFWorkbook();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            Sheet sheet = workbook.createSheet(sheetName);
            // 创建表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            // 创建表头
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 15 * 256); // 设置列宽
            }
            // 填充数据
            for (int i = 0; i < dataList.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Object obj = dataList.get(i);
                for (int j = 0; j < fields.length; j++) {
                    Cell cell = row.createCell(j);
                    Object value = getFieldValue(obj, fields[j]);
                    if (value != null) {
                        cell.setCellValue(value.toString());
                    }
                }
            }
            workbook.write(outputStream);
            return outputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }
    
    /**
     * 通过反射获取字段值
     */
    private static Object getFieldValue(Object obj, String fieldName) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(obj);
        } catch (Exception e) {
            return null;
        }
    }

    private static String getCellString(Row row, int col) {
        Cell cell = row.getCell(col);
        if (cell == null) return "";
        cell.setCellType(CellType.STRING);
        return cell.getStringCellValue().trim();
    }
}
